import {InjectEntityModel} from "@midwayjs/typeorm";
import Article from "../pojo/entity/article.entity";
import {Repository} from "typeorm";
import {Provide} from "@midwayjs/core";
import {ArticleInterface} from "../interface/Article";
import {getSql} from "../utils/SqlSplicingUtil";

/**
 * 关于文章的service层
 * @name: article.service
 * @data: 2024/4/11 9:31
 */
@Provide()
export class ArticleService {
  @InjectEntityModel(Article)
  articleModel: Repository<Article>


  /**
   * 新增文章
   *
   */
  async insertArticle(article: ArticleInterface) {
    console.log(23, article);
    return await this.articleModel.save(article);
  }

  /**
   * 根据文章id删除文章
   * @param id
   */
  async deleteArticleById(id: number) {
    return this.articleModel.delete(id);
  }

  /**
   * 更新文章
   * @param article
   */
  async updateArticle(article: ArticleInterface) {
    // console.log(getSql(article));
    // return
    return await this.articleModel.query(`update article set ${getSql(article)} where article_id=${article.articleId}`);
  }


  /**
   * 根据作者id查询文章列表
   * @param authorId
   */
  async selectArticleByAuthorId(authorId: number) {
    return await this.articleModel.findBy({authorId});
  }

  /**
   * 根据文章title查询文章列表
   * 支持模糊查询
   * @param title
   */
  async selectArticleByTitle(title: string) {
    return await this.articleModel.query(`select * from article where title like '%${title}%'`);
  }

  /**
   * 返回全部文章,无分页
   */
  async selectAllArticle() {
    return await this.articleModel.find();
  }

  /**
   * 增加文章喜欢数
   */
  async insertLikeCountById(articleId: number) {
    return await this.articleModel.query(`update article set like_count=like_count+1 where article_id=${articleId};`);
  }

  /**
   * 减少文章喜欢数
   * 注意这里我们写的SQL语句
   */
  async deleteLikeCountById(articleId: number){
    return await this.articleModel.query(`update article set like_count=like_count-1 where article_id=${articleId} and like_count>0;`);
  }

}
